# # 管理员中心接口
# from flask import current_app
# from flask import redirect
# from flask import render_template, jsonify
# from flask import request
# from flask import session
# from flask import url_for
#
# from info.models import User
# from info.modules.admin import admin_url
# from info.response_code import RET
#
#
# @admin_url.route('/login',methods=['GET','POST'])
# def admin_login():
#     if request.method=="GET":
#         return render_template("admin/login.html")
#     # TODO 登陆接口未完成
#     else:
#         username = request.form.get("username")
#         password = request.form.get("password")
#
#         if not all([username,password]):
#             return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
#
#         try:
#             user = User.query.filter(User.mobile ==username,User.is_admin==True).first()
#         except Exception as e:
#             current_app.logger.error(e)
#             return render_template('admin/login.html',errmsg='数据库查询错误')
#
#         if not user:
#             return render_template('admin/login.html',errmsg='未查询到用户信息')
#
#         if not user.check_passward(password):
#             return render_template('admin/login.html', errmsg="用户名或者密码错误")
#
#         session['user_id']=user.id
#         session['mobile']=username
#         session['nick_name']=username
#         session['is_admin']=user.is_admin
#
#         return redirect(url_for('admin.index'))
#         # return render_template('admin/index.html')
#
#
# @admin_url.route('/login')
# def index():
#     return render_template('admin/index.html')
import time
from datetime import datetime, timedelta

from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from sqlalchemy import and_

from info import constants, db
from info.models import User, News, Category
from info.modules.admin import admin_url
from info.response_code import RET
from info.utils.common import user_logo_data
from info.utils.image_storage import storage


@admin_url.route('/index')
@user_logo_data
def index():
    user = g.user

    return render_template('admin/index.html')


@admin_url.route('/login', methods=["GET", "POST"])
def login():
    """登陆页面"""
    if request.method == "GET":
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', None)
        if user_id and is_admin:
            return redirect(url_for('admin.index'))

        return render_template('admin/login.html')

    # 取到登录的参数
    username = request.form.get("username")
    password = request.form.get("password")

    # 判断参数
    if not all([username, password]):
        return render_template('admin/login.html', errmsg="参数错误")

    # 查询当前用户
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg="用户信息查询失败")

    if not user:
        return render_template('admin/login.html', errmsg="未查询到用户信息")

    # 校验密码
    if not user.check_passward(password):
        return render_template('admin/login.html', errmsg="用户名或者密码错误")

    # 保存用户的登录信息
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name
    session["is_admin"] = user.is_admin

    # 跳转到后面管理首页
    return redirect(url_for('admin.index'))


@admin_url.route('/user_count')
def user_count():
    # 总人数
    total_count = 0
    # 从数据库中查出用户总数
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    mon_count = 0
    t = time.localtime()
    begin_mon_time = datetime.strptime('%d-%02d-01' % (t.tm_year, t.tm_mon), '%Y-%m-%d')
    try:
        mon_count = User.query.filter(User.is_admin == False, User.create_time > begin_mon_time).count()
    except Exception as e:
        current_app.logger.error(e)

    day_count = 0
    begin_day_time = datetime.strptime('%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday), '%Y-%m-%d')
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > begin_day_time).count()
    except Exception as e:
        current_app.logger.error(e)

    t = datetime.now().strftime('%Y-%m-%d')
    now_date = datetime.strptime(t, '%Y-%m-%d')
    # 存放日期
    active_date = []
    # 存放人数
    active_count = []
    for i in range(1, 31):
        begin_day = now_date - timedelta(days=i)
        end_day = now_date - timedelta(days=(i - 1))
        active_date.append(begin_day.strftime('%Y-%m-%d'))
        count = User.query.filter(User.is_admin == False, and_(User.last_login >= begin_day,
                                                               User.last_login <= end_day)).count()
        active_count.append(count)

    active_count.reverse()
    active_date.reverse()
    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_date": active_date,
        "active_count": active_count
    }

    return render_template('admin/user_count.html', data=data)


@admin_url.route('/user_list')
def user_list():
    ''' 用户列表'''
    page = request.args.get('p', 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)

    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.create_time.desc()).paginate(page,
                                                                                                        constants.ADMIN_USER_PAGE_MAX_COUNT,
                                                                                                        False)
        users = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)

    user_list = []
    for user in users:
        user_list.append(user.to_admin_dict())

    data = {
        'users': user_list,
        'current_page': current_page,
        'total_page': total_page

    }
    return render_template('admin/user_list.html', data=data)


@admin_url.route('/news_review')
def news_review():
    """新闻审核"""
    page = request.args.get('p', 1)
    # 新闻搜索的关键字拿取
    keywords = request.args.get('keywords', '')

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
    # 新闻查询过滤条件添加
    filters = [News.status != 0]
    try:
        filters.append(News.title.contains(keywords))
    except Exception as e:
        current_app.logger.error(e)
    # 查询未审核通过的新闻
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                          constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                          False)
        news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)

    news_list = []
    for new in news:
        news_list.append(new.to_dict())

    data = {
        "news_list": news_list,
        "current_page": current_page,
        "total_page": total_page

    }

    return render_template('admin/news_review.html', data=data)


@admin_url.route('/news_review_detail', methods=['POST', 'GET'])
def news_review_detail():
    """新闻审核列表"""
    if request.method == 'GET':
        news_id = request.args.get('news_id')
        if not news_id:
            return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

            # 通过id查询新闻
        news = None

        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

        data = {
            'news': news.to_dict()
        }
        return render_template('admin/news_review_detail.html', data=data)


@admin_url.route('/news_review_action', methods=['POST'])
def news_review_action():
    news_id = request.json.get('news_id')
    active = request.json.get('action')
    if not all([news_id, active]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if active not in ['accept', 'reject']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if active == 'accept':
        news.status = 0
    else:
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        news.reason = reason
        news.status = -1

    try:
        db.session.commit()

    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@admin_url.route('/news_edit')
def news_list():
    page = request.args.get('p', 1)
    keywords = request.args.get('keywords')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    filters = [News.status == 0]
    if keywords:
        filters.append(keywords)
    current_page = ''
    total_page = ''
    content = ''
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                          constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                          False)
        current_page = paginate.page
        total_page = paginate.pages
        content = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    content_list = []
    for news in content:
        content_list.append(news)

    data = {
        'current_page': current_page,
        'total_page': total_page,
        'news_list': content_list
    }
    return render_template('admin/news_edit.html', data=data)


@admin_url.route('/news_edit_detail', methods=['POST', 'GET'])
def news_edit_detail():
    if request.method == 'GET':
        """新闻板式编辑"""
        news_id = request.args.get('news_id')
        if not news_id:
            return render_template('admin/news_edit_detail.html', data={"errmsg": "参数错误"})

        news = ''
        try:

            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return render_template('admin/news_edit_detail.html', data={"errmsg": "未查询到此新闻"})
        categories = []
        category = ''
        try:

            category = Category.query.all()
        except Exception as e:
            current_app.logger.error()

        for i in category:
            c_dict = i.to_dict()
            c_dict['is_selected'] = False
            if i.id == news.category:
                c_dict['is_selected'] = True
            categories.append(c_dict)

        categories.pop(0)

        data = {
            'news': news.to_dict(),
            "categories": categories
        }

        return render_template('admin/news_edit_detail.html', data=data)
    # post请求保存编辑的数据
    else:

        print('POST　请求')
        news_id = request.form.get("news_id")
        title = request.form.get("title")
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")

    if not all([title, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='参数错误')

    if index_image:
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='参数错误')

        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg='图片保存失败')
        news.index_image_url = 'http://pumiqhtfh.bkt.clouddn.com/' + key

    news.title = title
    news.digest = digest
    news.content = content

    news.category_id = category_id
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
        # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="编辑成功")


@admin_url.route('/news_category', methods=['POST', 'GET'])
def news_category():
    if request.method == 'GET':
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        category_li = []
        for category in categories:
            category_li.append(category.to_dict())

        data = {
            'categories': category_li
        }

        return render_template('admin/news_type.html', data=data)
    else:
        id = request.json.get('id')
        name = request.json.get('name')
        if not name:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if not id:
            try:
                category = Category()

                category.name = name
                db.session.add(category)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()
                return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")
            return jsonify(errno=RET.OK, errmsg='OK')

        else:
            try:
                category = Category.query.get(id)
            except Exception as e:
                current_app.logger.error(e)

                return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
            if not category:
                return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

            try:
                category.name = name
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()
                return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")
            return jsonify(errno=RET.OK, errmsg='OK')
